import utils from '../core/utils';
import logger from '../core/logger';
import common from '@ohos.app.ability.common';
import preferences from '@ohos.data.preferences';
import { downloadInfo } from '../models/manage/downloadInfo';

export default class downloadManager {
  private context: common.Context;
  private static _instance: downloadManager;

  public static get instance(): downloadManager {
    return this._instance;
  }

  public static createInstance(context: common.Context): downloadManager {
    if (this._instance == null)
      this._instance = new downloadManager(context);
    return this._instance;
  }

  private constructor(context: common.Context) {
    this.context = context;
  }

  saveData(info: downloadInfo) {
    preferences.getPreferences(this.context, 'download').then(async (preferences) => {
      let key = info.downloadId.toString();
      let value = await preferences.get(key, '');
      if (!utils.isEmpty(value)) {
        let di: downloadInfo = JSON.parse(value.toString());
        di.status = info.status;
        value = JSON.stringify(di);
      } else
        value = JSON.stringify(info);
      preferences.put(key, value);
      preferences.flush();
    }).catch((err) => logger.error(err));
  }

  delete(downloadId: number): Promise<void> {
    return new Promise((resolve) => {
      preferences.getPreferences(this.context, 'download').then(async (preferences) => {
        let key = downloadId.toString();
        await preferences.delete(key);
        preferences.flush();
        resolve();
      }).catch((err) => {
        logger.error(err);
        resolve();
      });
    });
  }

  getAllData(): Promise<Array<downloadInfo>> {
    return new Promise((resolve) => {
      let arr: Array<downloadInfo> = [];
      preferences.getPreferences(this.context, 'download').then(async (preferences) => {
        let value = await preferences.getAll();
        let values = Object.values(value);
        values.forEach((item) => {
          let di: downloadInfo = JSON.parse(item);
          arr.push(di);
        });
        resolve(arr);
      }).catch((err) => {
        logger.error(err);
        resolve(arr);
      });
    });
  }
}